import 'dart:io';

import 'package:chewie/chewie.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

import '../../../util/ImConstant.dart';

class VideoViewPage extends StatefulWidget {
  final String title;
  final String filePath;

  const VideoViewPage({required this.title, required this.filePath, super.key});

  @override
  State<StatefulWidget> createState() => PlayerViewState();
}

class PlayerViewState extends State<VideoViewPage> {
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;

  @override
  void initState() {
    _videoPlayerController = VideoPlayerController.file(File(widget.filePath));
    _videoPlayerController.initialize().then((_) {
      _chewieController = ChewieController(
        videoPlayerController: _videoPlayerController,
        autoPlay: true,
        looping: true,
      );

      setState(() {});
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: _buildAppBar(context),
        backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
        body: Center(
          child: buildVideoPane()
        ));
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      leading: GestureDetector(
        child: const Icon(Icons.chevron_left, color: Colors.black),
        onTap: () => Navigator.of(context).pop(),
      ),
      centerTitle: true,
      title: Text(
        widget.title,
        style: const TextStyle(color: Colors.black, fontSize: ImConstant.IM_DEFAULT_SIZE),
      ),
    );
  }

  Widget buildVideoPane() {
    if (_videoPlayerController.value.isInitialized) {
      return AspectRatio(
        aspectRatio: _videoPlayerController.value.aspectRatio,
        child: Chewie(
          controller: _chewieController,
        ),
      );
    } else {
      return const CircularProgressIndicator();
    }
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();
    super.dispose();
  }

}
